package com.first.agent.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.wf.captcha.SpecCaptcha;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/*
生成动态验证码
 */
@WebServlet("/captcha")
public class CaptchaServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ImageIO.setUseCache(false);
        //1.导入验证码依赖easy-captcha
        //验证码的宽，高，数字长度
        SpecCaptcha specCaptcha = new SpecCaptcha(120,40,4);
        //获取验证码的数字值
        String verCode = specCaptcha.text().toLowerCase();
        //存储session域中
        HttpSession session = request.getSession();
        session.setAttribute("serverVerCode",verCode);
        //利用工具类SpecCaptcha生成图片验证码
        Map map = new HashMap();
        map.put("image",specCaptcha.toBase64());
        //响应回来数据格式和编码
        response.setContentType("application/json;charset=utf-8");
        //用流方式写回去
        PrintWriter pw = response.getWriter();
        pw.write(JSONObject.toJSONString(map));
        pw.flush();
        pw.close();
    }
}
